using AutoMapper;
using MediatR;
using Medical.Api.Write.Application.Command.BasicManagement.DeviceDictionaryCommand;
using Medical.Domain.BasicManagement;
using Medical.ErrorCode;
using Medical.Interstructrue.Base;

namespace Medical.Api.Write.Application.Handler.BasicManagement.DeviceDictionaryHandler
{
    /// <summary>
    /// 更新设备状态处理器
    /// </summary>
    public class UpdateEquipmentStatusHandler : IRequestHandler<UpdateEquipmentStatusCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Equipment> _equipmentRepository;
        private readonly ILogger<UpdateEquipmentStatusHandler> _logger;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="equipmentRepository">设备仓储</param>
        /// <param name="logger">日志接口</param>
        /// <param name="mapper">AutoMapper接口</param>
        public UpdateEquipmentStatusHandler(
            IBaseRepository<Equipment> equipmentRepository,
            ILogger<UpdateEquipmentStatusHandler> logger,
            IMapper mapper)
        {
            _equipmentRepository = equipmentRepository;
            _logger = logger;
            _mapper = mapper;
        }

        /// <summary>
        /// 处理更新设备状态请求
        /// </summary>
        public Task<ApiResult<bool>> Handle(UpdateEquipmentStatusCommand request, CancellationToken cancellationToken)
        {
            // 1. 查找设备
            var equipment = _equipmentRepository.GetModel(request.StatusData.Id);
            if (equipment == null)
            {
                _logger.LogWarning($"无法更新设备状态，设备ID {request.StatusData.Id} 不存在");
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.NotFound,
                    Msg = $"设备不存在，ID: {request.StatusData.Id}",
                    Data = false
                });
            }

            // 2. 状态没有变化时，直接返回成功
            if (equipment.Status == request.StatusData.Status)
            {
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.Success,
                    Msg = $"设备状态无变化，当前状态: {(equipment.Status == 1 ? "启用" : "禁用")}",
                    Data = true
                });
            }

            // 3. 保存设备的原始用户信息
            var updateUserId = equipment.UpdateUserId;
            var updateUserName = equipment.UpdateUserName;
            
            // 4. 使用AutoMapper更新设备状态
            _mapper.Map(request.StatusData, equipment);
            
            // 5. 手动设置用户信息，确保不丢失
            equipment.UpdateUserId = updateUserId;
            equipment.UpdateUserName = updateUserName;
            
            var result = _equipmentRepository.Update(equipment) > 0;

            // 6. 返回结果
            if (result)
            {
                _logger.LogInformation($"设备状态更新成功，ID: {equipment.Id}, 状态: {(equipment.Status == 1 ? "启用" : "禁用")}");
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.Success,
                    Msg = $"设备状态已更新为: {(equipment.Status == 1 ? "启用" : "禁用")}",
                    Data = true
                });
            }
            else
            {
                _logger.LogError($"设备状态更新失败，ID: {equipment.Id}");
                return Task.FromResult(new ApiResult<bool>
                {
                    Code = ApiEnums.Fail,
                    Msg = "设备状态更新失败",
                    Data = false
                });
            }
        }
    }
}